package com.sen.common.log.filter;


import cn.hutool.core.util.StrUtil;
import com.sen.common.common.constrant.CommonConstrant;
import org.slf4j.MDC;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.core.annotation.Order;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author esjiang
 */
@ConditionalOnClass(Filter.class)
@Order(Integer.MIN_VALUE)
public class MdcTraceFilter extends OncePerRequestFilter {


    @Override
    protected boolean shouldNotFilter(HttpServletRequest request) {
        return true;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        try {
            String xTraceHeader = request.getHeader(CommonConstrant.X_TRACE_HEADER);
            if (StrUtil.isNotBlank(xTraceHeader)) {
                MDC.put(CommonConstrant.TRACE_NAME, xTraceHeader);
            }
            filterChain.doFilter(request, response);
        } finally {
            MDC.clear();
        }
    }
}
